<template>
  <div id="personManage">
    <div class="person-title">
      <div class="navTabs">
        <span class="admin-tab" :class="{ active: activeTab === 'admin' }"
          >管理员</span
        >
        <span
          class="training-user-tab"
          @click="handleTrainingUserTabClick()"
          :class="{ active: activeTab === 'trainingUser' }"
          >培训用户</span
        >
      </div>
      <div class="btns">
        <span class="addMember" @click="addAdminFn()">添加管理员</span>
        <span class="importMember" @click="importMemberFn()">批量导入</span>
        <span class="downloadTemplate" @click="downloadTemplate()"
          >模板下载</span
        >
      </div>
    </div>

    <div class="section-block">
      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="filter-item">
          <el-input
            v-model="searchGroupName"
            placeholder="输入关键字"
          ></el-input>
          <el-button type="primary" class="search-btn" @click="handleSearch()"
            >搜索</el-button
          >
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="userName" label="姓名" align="center" />
          <el-table-column prop="userNumber" label="工号" />
          <el-table-column prop="gender" label="性别">
            <template #default="{ row }">
              <span>{{ row.gender == 1 ? "男" : "女" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="操作" align="center" width="300">
            <template #default="{ row }">
              <div class="action-btns">
                <el-button
                  link
                  type="primary"
                  class="action-btn group-info-btn"
                  @click="initPassword(row)"
                >
                  <img
                    src="@/assets/img/institutionManagement/init-icon.png"
                    alt=""
                  />
                  初始化密码
                </el-button>
                <el-button
                  link
                  type="primary"
                  class="action-btn edit-btn"
                  @click="handleEdit(row)"
                >
                  <el-icon><Edit /></el-icon>
                  修改
                </el-button>
                <el-button
                  link
                  type="danger"
                  class="action-btn delete-btn"
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 批量导入 -->
    <el-dialog
      v-model="showImportDialog"
      width="650px"
      :close-on-click-modal="false"
    >
      <div class="import-content">
        <!-- 下载模板按钮 -->
        <div class="download-btn-box" @click="downloadTemplate">
          <img
            src="@/assets/img/institutionManagement/download-icon.png"
            alt=""
            class="btn-icon"
          />
          <span>下载模板</span>
        </div>

        <!-- 上传模板按钮 -->
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="false"
          accept=".xls,.xlsx"
          :limit="1"
        >
          <div class="upload-btn-box">
            <img
              src="@/assets/img/institutionManagement/upload-icon.png"
              alt=""
              class="btn-icon"
            />
            <span>点击上传</span>
          </div>
        </el-upload>

        <!-- 提示信息 -->
        <div class="import-tips">
          先下载模版，填写信息后上传，只能上传xls格式文件，且不超过50MB
        </div>

        <!-- 文件列表 -->
        <div class="file-list" v-if="uploadedFiles.length > 0">
          <div
            class="file-item"
            v-for="(file, index) in uploadedFiles"
            :key="index"
          >
            <img
              src="@/assets/img/institutionManagement/xls-icon.png"
              alt=""
              class="file-icon"
            />
            <span class="file-name">{{ file.name }}</span>
            <span class="file-size">{{ file.size }}</span>
            <span class="delete-icon"
              ><img
                src="@/assets/img/institutionManagement/close-icon.png"
                alt=""
                @click="removeFile(index)"
            /></span>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" color="#4F46E5" @click="handleSave"
            >保存</el-button
          >
          <el-button size="small" @click="showImportDialog = false"
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 添加/修改人员弹窗 -->
    <el-dialog
      v-model="showAddOrEditDialog"
      width="650px"
      :close-on-click-modal="false"
    >
      <div class="addOrEditDialog">
        <el-form
          :model="form"
          label-width="120px"
          :rules="rules"
          ref="addOrEditForm"
        >
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="工号" prop="userNumber">
            <el-input v-model="form.userNumber" placeholder="请输入工号" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option :value="1" label="男" />
              <el-option :value="2" label="女" />
            </el-select>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" color="#4F46E5" @click="handleSave"
            >保存</el-button
          >
          <el-button size="small" @click="showAddOrEditDialog = false"
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: "admin",
      searchGroupName: "",
      tableData: [
        {
          userName: "张伟",
          userNumber: "123456",
          gender: 1,
          phone: "12345678901",
          createTime: "2025-3.21 17:20",
        },
        {
          userName: "张伟",
          userNumber: "123456",
          gender: 2,
          phone: "12345678901",
          createTime: "2025-3.21 17:20",
        },
        {
          userName: "张伟",
          userNumber: "123456",
          gender: 2,
          phone: "12345678901",
          createTime: "2025-3.21 17:20",
        },
        {
          userName: "张伟",
          userNumber: "123456",
          gender: 1,
          phone: "12345678901",
          createTime: "2025-3.21 17:20",
        },
        {
          userName: "张伟",
          userNumber: "123456",
          gender: 1,
          phone: "12345678901",
          createTime: "2025-3.21 17:20",
        },
      ],
      showImportDialog: false,
      showAddOrEditDialog: false,
      form: {
        userName: "",
        userNumber: "",
        gender: 1,
        phone: "",
      },
      rules: {
        userName: [
          { required: true, message: "请输入人员姓名", trigger: "blur" },
        ],
        userNumber: [
          { required: true, message: "请输入工号", trigger: "blur" },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!/^(1[3-9]\d{9})$/.test(value)) {
                callback(new Error("请输入正确的手机号码"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
      },
      uploadedFiles: [
        {
          name: "测试文件.xls",
          size: "100KB",
        },
        {
          name: "测试文件.xls",
          size: "100KB",
        },
        {
          name: "测试文件.xls",
          size: "100KB",
        },
      ], // 上传的文件列表
      currentPage: 1, // 当前页
      pageSize: 10, // 每页条数
      total: 100, // 总条数
    };
  },
  methods: {
    handleTrainingUserTabClick() {
      this.$router.push("/personManage/trainingUser");
    },

    // 搜索
    handleSearch() {},

    // 初始化密码
    initPassword(row) {
      console.log("初始化密码", row);
    },

    // 修改
    handleEdit(row) {
      this.showAddOrEditDialog = true;
      this.form = {
        userName: row.userName,
        userNumber: row.userNumber,
        gender: row.gender,
        phone: row.phone,
      };
    },

    // 删除
    handleDelete(row) {
      console.log("删除", row);
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },

    // 添加人员
    addAdminFn() {
      this.showAddOrEditDialog = true;
      this.form = {
        userName: "",
        userNumber: "",
        gender: 1,
        phone: "",
      };
      if (this.$refs.addOrEditForm) {
        this.$refs.addOrEditForm.resetFields();
      }
    },

    // 批量导入
    importMemberFn() {
      this.showImportDialog = true;
      this.$nextTick(() => {
        if (this.$refs.uploadRef) {
          this.$refs.uploadRef.clearFiles();
        }
      });
    },

    // 下载模板
    downloadTemplate() {
      console.log("下载模板");
      // 这里添加下载模板的逻辑
    },

    // 处理文件变化（el-upload 组件回调）
    handleFileChange(file, fileList) {
      const maxSize = 50 * 1024 * 1024; // 50MB

      // 检查文件大小
      if (file.size > maxSize) {
        this.$message.error("文件大小不能超过50MB");
        this.$refs.uploadRef.clearFiles();
        return;
      }

      // 检查文件格式
      const fileName = file.name;
      const fileExtension = fileName.substring(fileName.lastIndexOf("."));
      if (![".xls", ".xlsx"].includes(fileExtension.toLowerCase())) {
        this.$message.error("只能上传xls格式文件");
        this.$refs.uploadRef.clearFiles();
        return;
      }

      // 格式化文件大小
      const formatSize = (size) => {
        if (size < 1024) {
          return size + "B";
        } else if (size < 1024 * 1024) {
          return (size / 1024).toFixed(2) + "KB";
        } else {
          return (size / (1024 * 1024)).toFixed(2) + "MB";
        }
      };

      // 添加到文件列表（只保留最新的一个文件）
      this.uploadedFiles = [
        {
          name: file.name,
          size: formatSize(file.size),
          file: file.raw,
        },
      ];
    },

    // 移除文件
    removeFile(index) {
      this.uploadedFiles.splice(index, 1);
      // 清空 el-upload 组件的文件列表
      if (this.$refs.uploadRef) {
        this.$refs.uploadRef.clearFiles();
      }
    },

    // 保存
    handleSave() {
      if (this.uploadedFiles.length === 0) {
        this.$message.warning("请先上传文件");
        return;
      }
      console.log("保存", this.uploadedFiles);
      // 这里添加上传文件的逻辑
      this.$message.success("导入成功");
      this.showImportDialog = false;
    },

    // 返回
    backFn() {
      this.$router.push("/institutionManage/groupInfo");
    },
  },
};
</script>

<style lang="scss" scoped>
#personManage {
  width: 1200px;
  margin: 0 auto;

  .person-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    height: 38px;
    .navTabs {
      display: flex;
      align-items: center;
      gap: 55px;
      .admin-tab,
      .training-user-tab {
        cursor: pointer;
        font-size: 18px;
        color: #252e54;
        &:hover {
          color: #4f46e5;
        }
        &.active {
          font-weight: bold;
          font-size: 18px;
          color: #4f46e5;
        }
      }
    }
    .text {
      font-weight: bold;
      font-size: 24px;
      color: #0a0a0a;
    }
    .addMember,
    .importMember {
      padding: 7px 18px;
      background: #4f46e5;
      border-radius: 4px;
      font-size: 16px;
      color: #ffffff;
      text-align: center;
      cursor: pointer;
      &:hover {
        background: #4338ca;
      }
    }

    .downloadTemplate {
      margin-left: 10px;
      padding: 7px 18px;
      background: #facc15;
      border-radius: 4px;
      font-size: 16px;
      color: #111827;
      text-align: center;
      cursor: pointer;
      &:hover {
        background: #eab308;
      }
    }

    .addMember {
      margin-right: 10px;
    }
  }

  .section-block {
    padding: 47px 57px 30px 45px;
    margin-bottom: 20px;
    box-shadow: 0px 0px 28px 1px rgba(0, 0, 0, 0.08);
    border-radius: 20px;
    background: #ffffff;
    box-sizing: border-box;

    // 筛选区域
    .filter-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 20px;
      margin-bottom: 40px;

      .filter-item {
        display: flex;
        align-items: center;
        gap: 20px;
      }

      .search-btn {
        margin-left: -10px;
        padding: 10px 20px;
        background: #4f46e5;
        border-color: #4f46e5;
        font-size: 14px;
        border-radius: 4px;
        &:hover {
          background: #4338ca;
          border-color: #4338ca;
        }
      }
    }

    // 表格区域
    .table-section {
      margin-bottom: 30px;

      :deep(.el-table) {
        font-size: 14px;

        .el-table__header th {
          padding: 12px 0;
          font-size: 14px;
          color: #000000;
          background-color: #f3f4f6;
        }

        .el-table__body td {
          padding: 12px 0;
          font-size: 14px;
          color: #000000;
        }
      }

      .action-btns {
        display: flex;
        align-items: center;
        justify-content: center;

        .action-btn {
          display: inline-flex;
          align-items: center;
          gap: 4px;
          font-size: 14px;
          padding: 4px 8px;

          .el-icon {
            font-size: 14px;
            margin-right: 4px;
          }
        }

        .group-info-btn {
          color: #3d78ff;
          img {
            width: 14px;
            height: 15px;
            margin-right: 4px;
          }
        }

        .edit-btn {
          color: #4f46e5;
        }

        .delete-btn {
          color: #ef4444;
        }
      }
    }

    // 分页区域
    .pagination-section {
      display: flex;
      align-items: center;
      justify-content: flex-end;

      :deep(.el-pagination) {
        .btn-prev,
        .btn-next,
        .el-pager li {
          &:hover {
            color: #4f46e5;
          }

          &.is-active,
          &.active {
            color: #4f46e5;
          }
        }
      }
    }
  }

  .addOrEditDialog {
    padding-right: 25px;
    padding-top: 10px;

    .my-data-picker-item {
      width: 80%;
    }
  }

  .assign-task-content {
    padding: 25px 20px;
  }

  // 批量导入弹窗样式
  :deep(.el-dialog) {
    border-radius: 8px;

    .el-dialog__body {
      padding: 20px 30px 30px;
    }
  }

  .import-content {
    color: #0a5ff6;
    font-size: 14px;
    .download-btn-box {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      height: 48px;
      background: #eff5ff;
      border-radius: 6px;
      border: 1px solid #c1d6fe;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s;
      box-sizing: border-box;

      .btn-icon {
        width: 16px;
        height: 16px;
      }
    }

    .upload-demo {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      height: 48px;
      background: #eff5ff;
      border-radius: 6px;
      border: 1px solid #c1d6fe;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s;
      box-sizing: border-box;

      .upload-btn-box {
        border: none;
        margin-bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
      }

      .btn-icon {
        width: 16px;
        height: 16px;
      }
    }

    .import-tips {
      font-size: 14px;
      color: #7b88a9;
      line-height: 36px;
      margin-bottom: 30px;
    }

    .file-list {
      .file-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px;
        background: #fff;
        border: 1px solid #e4e3e4;
        border-radius: 4px;
        margin-bottom: 8px;

        .file-icon {
          width: 27px;
          height: 33px;
          flex-shrink: 0;
        }

        .file-name {
          flex: 1;
          font-size: 14px;
          color: #383743;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .file-size {
          font-size: 12px;
          color: #676674;
          margin-right: 15px;
          flex-shrink: 0;
        }

        .delete-icon {
          width: 20px;
          height: 20px;
          cursor: pointer;
        }
      }
    }
  }
}
</style>